<?php

use app\helper\Rsa;
use app\model\User;
use Illuminate\Support\Str;
use Shopwwi\WebmanAuth\Facade\JWT as JwtFace;
use support\Log;
use support\Redis;
use support\Request;
use WebmanTech\Polyfill\LaravelRequest;


/**
 * 生成唯一邀请码
 */
function GetInvitationCode(): string
{
    $code = Str::random(7);

    if (User::where('invitation_code', $code)->exists()) {
        return GetInvitationCode();
    } else {
        return $code;
    }
}


/**
 * 生成唯一账号
 *
 * @return string
 */
function GetAccount(): string
{
    $account = Str::random(12);

    if (User::where('account', $account)->exists()) {
        return GetAccount();
    } else {
        return $account;
    }
}


/**
 * 生成唯一昵称
 *
 * @return string
 */
function GetNickname(): string
{
    $nickname = 'u_' . Str::random(10);

    if (User::where('nickname', $nickname)->exists()) {
        return GetNickname();
    } else {
        return $nickname;
    }
}


/**
 * 生成登录Token信息
 *
 * @param $userInfo
 * @param $ip
 * @param $platform
 * @return mixed
 */
function GenerateLoginToken($userInfo, $ip, $platform): mixed
{

    $userInfoKeyPrefix = config('redis.prefix') . ':GAME:USER:INFO:';

    $token = JwtFace::make([
        'id' => $userInfo['id'],
        'ulid' => $userInfo['ulid'],
        'account' => $userInfo['account'],
        'ip' => $ip,
        'client' => $platform,
    ]);
    Redis::del($userInfoKeyPrefix . $userInfo['ulid']);
    Redis::setNx($userInfoKeyPrefix . $userInfo['ulid'], serialize($userInfo));

    return $token;

}


/**
 * RSA加解密
 *
 * @param string $data // 操作数据
 * @param string $type // 操作类型 encode(加密) decode(解密)
 * @return string
 * @throws Exception
 */
function rsaCrypt(string $data, string $type = 'encode'): string
{

    $publicKey = file_get_contents(base_path('resource/rsa-crypt/public.key'));
    $privateKey = file_get_contents(base_path('resource/rsa-crypt/private.key'));

    try {
        $rsa = new Rsa();

        if ($type === 'decode') {
            return $rsa->rsa_decode($data, $privateKey);
        } else {
            return $rsa->rsa_encode($data, $publicKey);
        }
    } catch (Exception $e) {
        Log::info('操作失败：' . $e);
        throw new Exception('操作失败', 500);
    }

}


/**
 * AES加解密
 *
 * @param string $data // 操作数据
 * @param string $type // 操作类型 encode(加密) decode(解密)
 * @return string
 */
function aesCrypt(string $data, string $type = 'encode'): string
{

    $key = '072489d96c45a6c6';
    $iv = '302f290dae359114';

    if ($type === 'decode') {  // 解密
        return openssl_decrypt(base64_decode($data), 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    } else {  // 加密
        $encrypted = openssl_encrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
        return base64_encode($encrypted);
    }

}


/**
 * 请求参数验证
 *
 * @param Request $request
 * @param array $rules
 * @param array $messages
 * @return void
 * @throws Exception
 */
function requestValidator(Request $request, array $rules, array $messages = []): void
{

    $validator = validator(LaravelRequest::wrapper($request)->all(), $rules, $messages);
    if ($validator->fails()) {
        throw new Exception($validator->errors()->first(), 500);
    }

}

/**
 * 生成随机浮点数
 *
 * @param $min
 * @param $max
 * @return float|int|mixed
 */
function random_float($min = 0, $max = 1)
{
    return $min + lcg_value() * ($max - $min);
}